<template>
  <div class="music-detail-container">
    <!-- 顶部返回栏 -->
    <el-header class="detail-header">
      <div class="back-home" @click="$router.push('/findmusic')">
        <el-icon><ArrowLeft /></el-icon>
        <span>返回</span>
      </div>
    </el-header>

    <!-- 主要内容区域 -->
    <el-main class="main-content">
      <!-- 黑胶唱片 -->
      <div class="vinyl-container" :class="{ rotating: isPlaying }">
        <div class="vinyl-disc">
          <div class="vinyl-inner"></div>
          <img
            v-if="musicCover"
            :src="musicCover"
            class="album-cover"
            alt="album cover"
          />
        </div>
      </div>

      <!-- 歌曲信息 -->
      <div class="song-info">
        <h2 class="song-title">{{ name }}</h2>

        <p class="artist-name">{{ artist }}</p>
      </div>
      <el-icon
        class="favorite-icon"
        :style="{ color: isLiked ? '#ff4d4f' : '#666' }"
        @click="toggleLike"
      >
        <Star />
      </el-icon>

      <!-- 歌词区域 -->
      <!-- <div class="lyrics-box">
        <div class="lyrics-wrapper">
          <p
            v-for="(line, index) in lyrics"
            :key="index"
            :class="{ active: currentLyricIndex === index }"
            class="lyric-line"
          >
            {{ line }}
          </p>
        </div>
      </div> -->
    </el-main>

    <!-- 自定义音频控制 -->
    <div class="custom-audio-controls">
      <div v-if="isLoading" class="loading-container">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>正在加载音频...</span>
      </div>

      <audio
        ref="audioElement"
        :src="`http://localhost:3001/api/songs/${songPath}`"
        @error="handleAudioError"
        @timeupdate="handleTimeUpdate"
      ></audio>

      <p v-if="audioError" class="error-message">
        <el-icon><Warning /></el-icon>
        音频加载失败，请稍后重试
      </p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import axios from "axios";
import Plyr from "plyr";
import "plyr/dist/plyr.css";
import { ArrowLeft, Loading, Warning } from "@element-plus/icons-vue";
import { Star } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";

// 收藏状态
const isLiked = ref(false);
const route = useRoute();
const router = useRouter();
const id = ref(route.params.id);
const name = ref("");
const artist = ref("");
const songPath = ref("");
const lyrics = ref([]);
const currentLyricIndex = ref(0);
const isLoading = ref(true);
const audioError = ref(false);
const isPlaying = ref(false);
const audioElement = ref(null);
let player = null;

// 示例歌词数据
// const demoLyrics = [
//   "[00:00.00] 作词 : Demo Author",
//   "[00:10.00] 作曲 : Demo Composer",
//   "[00:20.00] ",
//   "[00:30.00] 这是示例歌词第一行",
//   "[00:40.00] 这是示例歌词第二行",
//   "[00:50.00] 这是示例歌词第三行",
//   "[01:00.00] ",
// ];
const toggleLike = async () => {
  if (!localStorage.getItem("userToken")) {
    ElMessage.warning("请先登录以收藏歌曲");
    return;
  }

  try {
    const userToken = localStorage.getItem("userToken");

    if (isLiked.value) {
      // 取消收藏
      await axios.delete(`http://localhost:3001/api/usersongs/${id.value}`, {
        headers: {
          Authorization: `Bearer ${userToken}`,
        },
      });
      ElMessage.success("取消收藏成功");
    } else {
      // 添加收藏
      await axios.post(
        "http://localhost:3001/api/usersongs",
        {
          songId: id.value,
          songTitle: name.value,
          songAuthor: artist.value,
          songPath: songPath.value,
        },
        {
          headers: {
            Authorization: `Bearer ${userToken}`,
          },
        }
      );
      ElMessage.success("收藏成功");
    }
    isLiked.value = !isLiked.value;
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败，请稍后重试");
    isLiked.value = !isLiked.value; // 回滚状态
  }
};
onMounted(async () => {
  try {
    const [detailRes, favoriteRes] = await Promise.all([
      axios.get(`http://localhost:3001/api/music/${id.value}`),
      axios.get(`http://localhost:3001/api/usersongs/check/${id.value}`, {
        headers: {
          Authorization: `Bearer ${localStorage.getItem("userToken")}`,
        },
      }),
    ]);

    const music = detailRes.data;
    name.value = music.songtitle;
    artist.value = music.songauthor;
    songPath.value = music.songpath;
    isLiked.value = favoriteRes.data.isLiked;
  } catch (error) {
    console.error("数据获取失败:", error);
  } finally {
    isLoading.value = false;
  }

  try {
    const response = await axios.get(
      `http://localhost:3001/api/music/${id.value}`
    );
    const music = response.data;
    name.value = music.songtitle;
    artist.value = music.songauthor;
    songPath.value = music.songpath;

    // 初始化播放器
    if (audioElement.value) {
      player = new Plyr(audioElement.value, {
        controls: [
          "play",
          "progress",
          "current-time",
          "duration",
          "mute",
          "volume",
        ],
        volume: 0.7,
      });

      player.on("play", () => (isPlaying.value = true));
      player.on("pause", () => (isPlaying.value = false));
    }

    // 解析歌词
    lyrics.value = parseLyrics(demoLyrics);
  } catch (error) {
    console.error("数据获取失败:", error);
  } finally {
    isLoading.value = false;
  }
});

onUnmounted(() => {
  if (player) player.destroy();
});

const parseLyrics = (rawLyrics) => {
  return rawLyrics
    .map((line) => {
      return line.replace(/\[\d{2}:\d{2}\.\d{2}\]/, "").trim();
    })
    .filter((line) => line);
};

const handleTimeUpdate = () => {
  if (!player) return;
  const currentTime = player.currentTime;
  // 这里需要实现歌词时间同步逻辑
  // 示例：currentLyricIndex.value = findCurrentLyricIndex(currentTime);
};

//歌词加载失败方法
// const handleAudioError = () => {
//   audioError.value = true;
// };
</script>

<style lang="scss" scoped>
$primary-color: #ff4d4f;
$dark-bg: #1a1a1a;
$text-primary: #ffffff;

.music-detail-container {
  height: 100vh;
  background: linear-gradient(45deg, #0a0a0a 0%, #1a1a1a 100%);
  color: $text-primary;
  display: flex;
  flex-direction: column;
  position: relative;
}

.detail-header {
  height: 60px;
  padding: 0 2rem;
  border-bottom: 1px solid #333;
  display: flex;
  align-items: center;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(5px);

  .back-home {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
    transition: all 0.3s;
    padding: 8px 12px;
    border-radius: 8px;

    &:hover {
      background: rgba(255, 76, 79, 0.1);
      color: $primary-color;

      .el-icon {
        color: inherit;
        transform: translateX(-3px);
      }
    }

    span {
      font-size: 1.1rem;
      font-weight: 500;
    }

    .el-icon {
      font-size: 1.4rem;
      transition: transform 0.3s;
    }
  }
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 2rem 0;
  overflow: hidden;
}

.vinyl-container {
  width: 320px;
  height: 320px;
  margin-bottom: 2rem;
  position: relative;
  perspective: 1000px;

  .vinyl-disc {
    position: relative;
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background: radial-gradient(
      circle at 50% 50%,
      #000 55%,
      darken($primary-color, 15%) 100%
    );
    box-shadow: 0 0 30px rgba(0, 0, 0, 0.8), inset 0 0 30px rgba(0, 0, 0, 0.7);
    transform-style: preserve-3d;

    &::after {
      content: "";
      position: absolute;
      inset: 0;
      border-radius: 50%;
      background: repeating-radial-gradient(
        circle at 50%,
        transparent 0,
        transparent 3px,
        rgba(255, 255, 255, 0.15) 3px,
        rgba(255, 255, 255, 0.15) 6px
      );
      animation: vinyl-line 4s linear infinite;
      mix-blend-mode: overlay;
    }

    &::before {
      content: "";
      position: absolute;
      top: -3px;
      left: 50%;
      transform: translateX(-50%);
      width: 4px;
      height: 25px;
      background: $primary-color;
      box-shadow: 0 0 15px $primary-color;
      z-index: 2;
      border-radius: 2px;
    }
  }

  .vinyl-inner {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background: #000;
    border: 4px solid $primary-color;
    box-shadow: inset 0 0 20px rgba(255, 76, 79, 0.5),
      0 0 30px rgba(255, 76, 79, 0.3);
  }

  .album-cover {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 50%;
    height: 50%;
    border-radius: 50%;
    object-fit: cover;
    box-shadow: 0 0 30px rgba(0, 0, 0, 0.7);
    border: 2px solid rgba(255, 76, 79, 0.5);
    z-index: 1;
  }
}

.rotating {
  animation: vinyl-rotate 12s linear infinite;

  .vinyl-disc::after {
    animation: vinyl-rotate 12s linear infinite reverse,
      vinyl-line 4s linear infinite;
  }
}

@keyframes vinyl-rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@keyframes vinyl-line {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.favorite-icon {
  position: absolute;
  top: 570px;
  transform: translateY(-50%);
  font-size: 2rem;
  cursor: pointer;
  transition: all 0.3s;
  &:hover {
    transform: translateY(-50%) scale(1.2);
  }
}
.song-info {
  text-align: center;
  margin-bottom: 2rem;
  position: relative;

  .song-title {
    display: inline-block;

    font-size: 2rem;
    margin-bottom: 0.5rem;
    letter-spacing: 1px;
    text-shadow: 0 2px 8px rgba(0, 0, 0, 0.7);
  }

  .artist-name {
    color: #888;
    font-size: 1.2rem;
    letter-spacing: 0.5px;
  }
}

// .lyrics-box {
//   width: 80%;
//   max-width: 600px;
//   height: 200px;
//   margin: 0 auto;
//   padding: 0 15px;
//   overflow: hidden;
//   position: relative;

//   .lyrics-wrapper {
//     transition: transform 0.5s cubic-bezier(0.22, 0.61, 0.36, 1);
//     will-change: transform;
//   }

//   .lyric-line {
//     text-align: center;
//     color: #666;
//     line-height: 2;
//     transition: all 0.3s;
//     margin: 12px 0;
//     padding: 0 20px;
//     font-size: 1.1rem;
//     transform-origin: center;

//     &.active {
//       color: $primary-color;
//       font-size: 1.3rem;
//       transform: scale(1.08);
//       text-shadow: 0 0 12px rgba(255, 76, 79, 0.4);
//       font-weight: 500;
//     }
//   }

//   &::-webkit-scrollbar {
//     display: none;
//   }
// }

:deep(.plyr) {
  --plyr-color-main: #{$primary-color};
  --plyr-audio-controls-background: #{rgba(0, 0, 0, 0.95)};
  --plyr-audio-control-color: #{$text-primary};
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  padding: 15px 0;
  backdrop-filter: blur(8px);
  border-top: 1px solid rgba(255, 76, 79, 0.2);

  .plyr__progress__container {
    border-radius: 8px;
    height: 6px;
    margin: 0 20px 8px;
    background: rgba(255, 255, 255, 0.1);
    transition: height 0.3s;

    &:hover {
      height: 8px;
    }
  }

  .plyr__progress__played {
    background: linear-gradient(
      90deg,
      lighten($primary-color, 5%) 0%,
      darken($primary-color, 10%) 100%
    );
    border-radius: 8px;
  }

  .plyr__control {
    transition: all 0.2s;

    &:hover {
      background: rgba(255, 255, 255, 0.1);
      transform: scale(1.1);
    }

    &.plyr__tab-focus {
      box-shadow: 0 0 0 3px rgba(255, 76, 79, 0.5);
    }
  }

  .plyr__time {
    font-size: 0.9em;
    padding: 0 12px;
  }

  .plyr__volume input[type="range"] {
    &::-webkit-slider-runnable-track {
      background: linear-gradient(
        90deg,
        $primary-color 0%,
        darken($primary-color, 15%) 100%
      );
    }
  }
}

.error-message {
  position: fixed;
  bottom: 100px;
  width: 100%;
  text-align: center;
  color: $primary-color;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  font-size: 1.1rem;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.loading-container {
  position: fixed;
  bottom: 50%;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  gap: 8px;
  color: #888;
  font-size: 1.1rem;
  background: rgba(0, 0, 0, 0.8);
  padding: 12px 24px;
  border-radius: 8px;
  backdrop-filter: blur(4px);
}
</style>
